#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：刘骏轩2025讯飞
@File ：VideoOperator.pyls

@Author ：ljx
@Date ：2025/7/25 下午9:30
'''

# try:
#     import queue  # Python 3
# except ImportError:
#     import Queue as queue  # Python 2
import queue
import threading
import cv2
import numpy as np
'''
这个代码作为一个摄像头调用的模板代码，用于新建线程处理摄像头的图片
'''
class videoOperator:
    def __init__(self):
        self.ImagesQueue = queue.Queue(maxsize=1)  # 限制队列大小避免堆积
        self.threadingRunning = False
        self.thread = None
        self.lock = threading.Lock()  # 添加线程锁
        self.StartThreading()

    def StartThreading(self):
        if not self.threadingRunning:
            print("启动子线程")
            self.thread = threading.Thread(target=self.threadingWork)
            self.thread.daemon = True  # 设置为守护线程
            self.thread.start()

    def StopThreading(self):
        if self.threadingRunning:
            self.threadingRunning = False
            self.thread.join()
            print("子线程关闭")

    def threadingWork(self):
        print("视频流处理子线程")
        self.threadingRunning = True
        cap = cv2.VideoCapture(0)
        try:
            while self.threadingRunning:
                ret, frame = cap.read()
                if not ret:
                    continue
                frame = cv2.flip(frame, 1)

                # 清空队列只保留最新帧
                with self.lock:#获取线程锁
                    while not self.ImagesQueue.empty():# 循环检查队列是否为空
                        try:
                            self.ImagesQueue.get_nowait()# 非阻塞式移除队首元素
                        except queue.Empty:# 队列为空则退出
                            break
                    self.ImagesQueue.put(frame)# 将新帧放入队列
        finally:
            cap.release()
            print("视频流已释放")

    def Get_Image(self):
        # 非阻塞获取图像
        with self.lock:  # 线程锁，保证资源的访问与释放
            if not self.ImagesQueue.empty():
                img = self.ImagesQueue.get_nowait()
                return img
            else:
                return None


if __name__ == '__main__':
    pass
